// Created by Joe on 2017/7/17.

app.controller(
    'WeatherController',
    [
        'KEY', 'config', '$scope', '$location', '$filter', '$timeout', '$sce', 'WeatherService',
        function (KEY, config, $scope, $location, $filter, $timeout, $sce, WeatherService) {
            init();

            function init() {
                // set weather_prediction map
                $scope.PredictionMap = {
                    0: 'sunny',
                    1: 'cloudy',
                    2: 'overcast',
                    3: 'middling-rain',
                    4: 'thundershower',
                    5: 'hailstone',
                    6: 'rain-snow',
                    7: 'light-rain',
                    8: 'middling-rain',
                    9: 'heavy-rain',
                    10: 'rainstorm',
                    11: 'rainstorm',
                    12: 'extra-rainstorm',
                    13: 'middling-snow',
                    14: 'light-snow',
                    15: 'middling-snow',
                    16: 'heavy-snow',
                    17: 'heavy-snowstorm',
                    18: 'fog',
                    29: 'floating-dust',
                    31: 'sand-dust',
                    u1: 'wind',
                    u2: 'high-wind',
                    u3: 'tornado',
                    u4: 'hurricane',
                    u5: 'haze'
                };

                // set weather_warning map
                // $scope.WarningMap = {};

                // set city
                $scope.curCity = config.curCity;

                // set move
                $scope.position = config.Weather;

                // set page
                // @dl: detail list
                // @dli: detail list item
                $scope.page = ['prediction', 'warning'];
                $scope.panel = {load: false, empty: false};
                $scope.limit = {list: 4};
                $scope.control = {page: 0, menu: 1, hold: 0, dl: 0, dli: 0, mask: false, height: 0};

                // current position
                $scope.cp = $scope.position[$scope.page[$scope.control.page]];

                // set focus
                // @ci: current id
                $scope.focus = {ci: $scope.cp[0].id};

                // set data
                $scope.data = {
                    date: generatorDateList(),
                    time: '',
                    weather: [],
                    warning: [],
                    curWarning: [],
                    provinceWarning: [],
                    cityWarning: [],
                    warningDetail: {}
                };

                // get info
                $scope.panel.load = true;
                WeatherService.getWeatherPrediction()
                    .then(function (info) {
                        $scope.data.time = $filter('mul_date')(info.time, 2);
                        $scope.data.weather = info.weather.slice(0, 7);
                        var highArr = [], lowArr = [];
                        $scope.data.weather.forEach(function (w) {
                            highArr.push(w.Htem);
                            lowArr.push(w.Ltem);
                            draw(highArr, lowArr);
                        });

                        $scope.panel.load = false;
                    });

                // add logic
                addLogic();

                // silent process
                // load method: when load this page,
                // request prediction and warning simultaneously,
                // before prediction finish request, forbidden focus move
                // but there may exit some problems, ignore them :)
                $timeout(function () {
                    config.silentProcess && $scope.refreshWarning();
                }, 10000);

                // ele action
                $scope.move = function (evt, cb) {
                    evt.preventDefault();
                    if ($scope.control.mask) return;

                    switch (evt.keyCode) {
                        case KEY.LEFT:
                            if (evt.target.id === 'wn-link') {
                                $scope.panel.load = false;
                                moveShim('left');
                                pageSwitch(0);
                            } else if (evt.target.id.indexOf('dli') !== -1) {
                                moveShim('left', 'dynamic')
                            }
                            break;
                        case KEY.RIGHT:
                            if (evt.target.id === 'wp-link') {
                                if ($scope.control.load) return;
                                if ($scope.data.warning.length === 0) $scope.refreshWarning();
                                moveShim('right');
                                pageSwitch(1);
                            } else if (evt.target.id.indexOf('ww') !== -1 && $scope.data.warning.length > 0) {
                                moveShim('right', 'dli')
                            }
                            break;
                        case KEY.UP:
                            if (evt.target.id === 'ww-1') {
                                moveShim('up');
                                document.getElementById('wn-link').className = '';
                                document.getElementById('wn-line').style.display = 'none';
                            } else if (evt.target.id === 'ww-2') {
                                moveShim('up');
                                $scope.control.menu--;
                                $scope.switchWarning(true);
                            } else if (evt.target.id.indexOf('dli') !== -1) {
                                if ($scope.control.dli === 0 && $scope.control.dl > 0) {
                                    $scope.data.curWarning =
                                        $scope.data.warning.slice(
                                            --$scope.control.dl,
                                            $scope.control.dl + $scope.limit.list);
                                } else {
                                    moveShim('up', 'dli');
                                }
                            }
                            break;
                        case KEY.DOWN:
                            if (evt.target.id === 'wn-link') {
                                moveShim('down');
                                document.getElementById('wn-link').className = 'hold';
                                document.getElementById('wn-line').style.display = 'inline-block';
                            } else if (evt.target.id === 'ww-1') {
                                moveShim('down');
                                $scope.control.menu++;
                                $scope.switchWarning();
                            } else if (evt.target.id.indexOf('dli') !== -1) {
                                if ($scope.control.dli === 3
                                    && $scope.control.dl < $scope.data.warning.length - $scope.limit.list) {
                                    $scope.data.curWarning =
                                        $scope.data.warning.slice(
                                            ++$scope.control.dl,
                                            $scope.control.dl + $scope.limit.list);
                                } else {
                                    moveShim('down', 'dli');
                                }
                            }
                            break;
                        case KEY.ENTER:
                            cb instanceof Function && cb();
                            break;
                    }
                };

                // global action
                document.addEventListener('keydown', globalAction);
            }

            function addLogic() {
                // get warning
                $scope.getWarning = function (city, cb) {
                    $scope.panel.load = true;
                    WeatherService.getWeatherWarning(city && config.curCity.cityName, city && config.curCity.stationID)
                        .then(function (info) {
                            $scope.panel.load = false;
                            cb instanceof Function && cb(info);
                            if (city) $scope.data.cityWarning = info;
                            else $scope.data.provinceWarning = info;
                        });
                };
                $scope.refreshWarning = function () {
                    $scope.getWarning();
                    $scope.getWarning(true, function (info) {
                        $scope.data.warning = info;
                        $scope.data.curWarning =
                            $scope.data.warning.slice(
                                $scope.control.dl,
                                $scope.control.dl + $scope.limit.list);
                        $scope.panel.empty = $scope.data.curWarning.length === 0;
                    });
                };

                // switch waring
                $scope.switchWarning = function (city) {
                    if (city)
                        $scope.data.warning = $scope.data.cityWarning;
                    else
                        $scope.data.warning = $scope.data.provinceWarning;
                    $scope.control.dl = 0;
                    $scope.control.dli = 0;
                    $scope.data.curWarning =
                        $scope.data.warning.slice(
                            $scope.control.dl,
                            $scope.control.dl + $scope.limit.list);
                    $scope.panel.empty = $scope.data.curWarning.length === 0;
                };

                // view warning detail
                $scope.viewWarningDetail = function () {
                    var warning = $scope.data.curWarning[$scope.control.dli];
                    $scope.data.warningDetail.icon = warning.YjHissignal;
                    $scope.data.warningDetail.title = warning.YjTitle;
                    $scope.data.warningDetail.updateTime = warning.YjIssuedate;
                    $scope.data.warningDetail.detail = warning.YjContent;
                    $scope.data.warningDetail.guide = $sce.trustAsHtml(
                        '防御指南<br>' + warning.YjContentnotic.substr(5).replace(/；/g, ';<br>'));
                    $scope.control.mask = true;
                    $timeout(function () {
                        $scope.control.height = parseInt($('.city__weather-mb').css('height')) + 215;
                    });
                };
            }

            function pageSwitch(page) {
                page = page || 0;
                $scope.control.page = page;
                $scope.cp = $scope.position[$scope.page[$scope.control.page]];
            }

            function generatorDateList() {
                var padding = function (str, len) {
                    str = str || '';
                    len = len || 2;
                    var dis = str.length - len;
                    while (dis-- > 0) str = '0' + str;
                    return str;
                };
                var weekMap = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];

                var list = [];
                var date = new Date();
                var today = date.getDay();
                // date.setDate(date.getDate() - date.getDay() + 1);
                for (var d = 0; d < 7; d++) {
                    d !== 0 && date.setDate(date.getDate() + 1);
                    list.push({
                        week: today === date.getDay() ? '今天'
                            : today === date.getDay() - 1 ? '明天' : weekMap[date.getDay()],
                        day: [padding((date.getMonth() + 1).toString()), padding(date.getDate().toString())].join('/')
                    });
                }

                return list;
            }

            function draw(hArr, lArr) {
                var canvas = $('#weather_draw')[0];
                var highStart = {x: 79, y: 85};
                var lowStart = {x: 79, y: 165};
                drawLine(canvas.getContext('2d'), highStart, hArr, 'rgba(230, 91, 79, .5)');
                drawLine(canvas.getContext('2d'), lowStart, lArr, 'rgba(70, 158, 215, .5)');
            }

            function drawLine(ctx, start, dotArr, lineColor) {
                var dotMargin = 158;
                ctx.lineWidth = 4;
                ctx.strokeStyle = lineColor;
                ctx.font = '20px sans-serif';

                var posX, posY, posDot = [];
                // draw line
                ctx.beginPath();
                dotArr.map(function (dot, index) {
                    posX = start.x + index * dotMargin;
                    posY = start.y + (30 - dot) * 5;
                    posDot.push({x: posX, y: posY});
                    if (index === 0) {
                        ctx.moveTo(posX, posY);
                    } else {
                        ctx.lineTo(posX, posY);
                    }
                });
                ctx.stroke();

                // draw dot
                posDot.map(function (pd, index) {
                    ctx.beginPath();
                    ctx.fillStyle = '#f0f0f0';
                    ctx.arc(pd.x, pd.y, 6, 0, Math.PI * 2);
                    ctx.fill();
                    ctx.fillStyle = '#9a9b9e';
                    ctx.fillText(dotArr[index] + '℃', pd.x - 20, pd.y - 20);
                });
            }

            function moveShim(dir, type) {
                type = type || 'static';
                if (type === 'static') {
                    var curFocus = $scope.cp.filter(function (item) {
                        return item.id === $scope.focus.ci;
                    })[0];
                    if (curFocus['move'][dir] !== -1) {
                        $scope.focus.ci = curFocus['move'][dir];
                    }
                } else {
                    switch (dir) {
                        case 'left':
                            $scope.control.hold = 0;
                            $scope.focus.ci = ['ww', $scope.control['menu']].join('-');
                            break;
                        case 'right':
                            $scope.control.hold = $scope.control['menu'];
                            $scope.focus.ci = [type, $scope.control[type]].join('-');
                            break;
                        case 'up':
                            if ($scope.control[type] > 0) {
                                $scope.focus.ci = [type, --$scope.control[type]].join('-');
                            }
                            break;
                        case 'down':
                            if ($scope.control[type] < $scope.limit.list - 1) {
                                $scope.focus.ci = [type, ++$scope.control[type]].join('-');
                            }
                            break;
                    }
                }
            }

            function globalAction() {
                if (event.keyCode === KEY.UP) {
                    if ($scope.control.mask) {
                        $('.city__weather-scroll').css('height', 690);
                    }
                }

                if (event.keyCode === KEY.DOWN) {
                    if ($scope.control.mask && $scope.control.height > 690) {
                        $('.city__weather-scroll').css('height', $scope.control.height);
                    }
                }

                if (event.keyCode === KEY.BACK) {
                    event.preventDefault();

                    if ($scope.control.mask) {
                        $scope.$apply(function () {
                            $scope.control.mask = false;
                            $scope.control.height = 0;
                        });
                        return;
                    }

                    $scope.$apply(function () {
                        $location.path('/home').replace();
                    });
                }

                $scope.$digest();
            }

            $scope.$on('$destroy', function () {
                document.removeEventListener('keydown', globalAction);
            });
        }
    ]
);